package com.demo.config;

import javax.sql.DataSource;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

@Configuration
@MapperScan(basePackages = { "com.demo.mapper.ztm" }, sqlSessionFactoryRef = "ztmSqlSessionFactory")
public class ZtmMybatisConfiguration {

	@Autowired
	@Qualifier("ztm")
	private DataSource dataSource;
	
	@Bean(name = "ztmSqlSessionFactory")
	public SqlSessionFactoryBean sqlSessionFactory(@Value("${mybatis.ztm.mapperLocations}") String mapperLocations, 
			@Value("${mybatis.ztm.typeAliasesPackage}")String typeAliasesPackage) throws Exception {
		SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
		sessionFactoryBean.setDataSource(dataSource);
		sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
		sessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
		return sessionFactoryBean;
	}

	@Bean(name = "ztmTransactionManager")
	public DataSourceTransactionManager transactionManager() {
		return new DataSourceTransactionManager(dataSource);
	}
}
